package com.nnxy.worktostudy.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.nnxy.worktostudy.security.entity.SecurityUser;
import com.nnxy.worktostudy.security.security.TokenManager;
import com.nnxy.worktostudy.system.entity.Admin;
import com.nnxy.worktostudy.utils.ResponseFormat;
import com.nnxy.worktostudy.utils.ResponseUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @Author : lu'qz
 * @create 2021/9/22 18:13
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private TokenManager tokenManager;
    private AuthenticationManager authenticationManager;

    public TokenLoginFilter(TokenManager tokenManager, AuthenticationManager authenticationManager) {
        this.tokenManager = tokenManager;
        this.authenticationManager = authenticationManager;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/system/login","POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            Admin admin = new ObjectMapper().readValue(request.getInputStream(), Admin.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(admin.getUsername(),admin.getPassword(),
                    new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        SecurityUser user = (SecurityUser) authResult.getPrincipal();
        String token = tokenManager.sign(user.getCurrentUserInfo().getId());
        ResponseFormat r = ResponseFormat.succeed();
        r.getData().put("token",token);
        ResponseUtil.out(response, r);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        ResponseFormat r = ResponseFormat.failed().setMessage("登录失败！");
        if ("Bad credentials".equals(failed.getMessage())) {
            r = r.setMessage("用户名或密码错误！");
        }
        ResponseUtil.out(response, r);
    }
}
